<?php
$host = '127.0.0.1';
$port = 3128;
$password = 'password';
$userid = 'rendong';
$username = '用户名ddd';

$fp = fsockopen($host, $port, $errno, $errstr, 30);
if (!$fp) {
    echo "$errstr ($errno)<br />\n";
} else {
	echo "connect success\n";
	$message = s(100) . str($userid) . str($username) . str($password);
	$out = i(strlen($message)) . $message;

    fwrite($fp, $out);
/**
	$len = current(unpack("i", fread($fp, 4)));
	echo 'len:' . $len;
	$data = unpack("stype/istatus", fread($fp, $len));
	echo "return type:{$data['type']}, status:{$data['status']}\n";
**/
	$channel = 'world';
	$content = str_repeat("a", 512);
	$message = s(103) . str($channel) . str($content); // 频道聊天
	//$message = s(104) . str($userid) . str($content); // 私聊
	$out = i(strlen($message)) . $message;
	echo "write content length:" . strlen($content) .' message length:' . (strlen($out) ) . "\n";

$start_t = microtime(true);
for($i = 0; $i< 5; $i++)
{
	fwrite($fp, $out);	
}
echo "finish:" . (microtime(true) - $start_t) . "s\n";
sleep(2);
exit;

	while(true){
	$len = current(unpack("i", fread($fp, 4)));// %d%hd %d%s%d%s%d%s
	$type = current(unpack("s", fread($fp, 2)));
//// len+type+srcUserID+srcUserName+name+message
	$len_uid = current(unpack("i", fread($fp, 4)));
	$str_uid = current(unpack("a" . $len_uid, fread($fp, $len_uid)));
	
	$len_username = current(unpack("i", fread($fp, 4)));
	$str_username = current(unpack("a" . $len_username, fread($fp, $len_username)));
	
	$len_name = current(unpack("i", fread($fp, 4)));
	$str_name = current(unpack("a" . $len_name, fread($fp, $len_name)));

	$len_msg = current(unpack("i", fread($fp, 4)));
	$str_msg = current(unpack("a" . $len_msg, fread($fp, $len_msg)));
	
	echo "message,type:{$type} uid:{$str_uid} username:{$str_username} name:{$str_name} msg:{$str_msg}\n";
	}

    fclose($fp);
}

// 封装字符串
function str($str)
{
	return pack("i",strlen($str)) .   $str;
}

// 封装int
function i($i)
{
	return pack("i", $i);
}

// 封装short
function s($s)
{
	return pack("s", $s);
}
?>
